﻿using CodeGenerator.BaseUI;
using CodeGenerator.Common;
using CodeGenerator.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace CodeGenerator.UI
{
    public partial class FrmCreateBuildH : BaseFormEx
    {
        public FrmCreateBuildH()
        {
            InitializeComponent();
        }

        public BackgroundWorker doWork = null;
        Dictionary<string, string> content = new Dictionary<string, string>();
        BuildHCodeCreate model = null;
        string outputDir = "";
        bool preview = false;

        AutoSizeFormClass asc = new AutoSizeFormClass();

        private void FrmCreateBuildH_Load(object sender, EventArgs e)
        {
            ucListControl1.Visible = false;
            ucFormControl1.Visible = false;
            ChangeBtnState();

            asc.controllInitializeSize(this);
        }

        private void ChangeBtnState()
        {
            if (ucBasicControl1.Visible)
            {
                btnPrev.Enabled = false;
                btnNext.Enabled = true;
                btnOk.Enabled = false;
            }
            else if (ucListControl1.Visible)
            {
                btnPrev.Enabled = true;
                btnNext.Enabled = true;
                btnOk.Enabled = false;
            }
            else if (ucFormControl1.Visible)
            {
                btnPrev.Enabled = true;
                btnNext.Enabled = false;
                btnOk.Enabled = true;
            }
        }

        private void ChangeDisplayState(bool isPrev)
        {

            if (isPrev)
            {
                if (ucListControl1.Visible)
                {
                    ucBasicControl1.Visible = true;
                    ucListControl1.Visible = false;
                    ucFormControl1.Visible = false;

                }
                else if (ucFormControl1.Visible)
                {
                    ucBasicControl1.Visible = false;
                    ucListControl1.Visible = true;
                    ucFormControl1.Visible = false;
                }
            }
            else
            {
                if (ucBasicControl1.Visible)
                {
                    ucBasicControl1.Visible = false;
                    ucListControl1.Visible = true;
                    ucFormControl1.Visible = false;
                }
                else if (ucListControl1.Visible)
                {
                    ucListControl1.Visible = false;
                    ucListControl1.Visible = false;
                    ucFormControl1.Visible = true;
                }
            }
            ChangeBtnState();
        }

        #region 按钮组
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnPrev_Click(object sender, EventArgs e)
        {
            ChangeDisplayState(true);
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            ChangeDisplayState(false);
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            content.Clear();
            progressBar1.Visible = true;

            progressBar1.Minimum = 0;
            progressBar1.Maximum = 8;
            doWork = new BackgroundWorker();
            doWork.DoWork += doWork_DoWork;
            doWork.ProgressChanged += doWork_ProgressChanged;
            doWork.RunWorkerCompleted += doWork_RunWorkerCompleted;
            doWork.WorkerReportsProgress = true;//此属性必须设置，否则读取不到进度
            doWork.WorkerSupportsCancellation = true; // 运行取消操作

            Dictionary<string, object> dict = ucBasicControl1.GetBasicData();
            Dictionary<string, bool> btn = ucListControl1.GetBtnInfo();
            List<CreateListCode> listCode = ucListControl1.GetListCode();
            List<CreateFormCode> formCode = ucFormControl1.GetFormCode();

            model = new BuildHCodeCreate();
            model.TableInfo = ucBasicControl1.tableInfo;
            model.Name = model.TableInfo.Name;
            model.NameSpace = dict["NameSpace"].ToString();
            model.AreaName = dict["AreaName"].ToString();

            string[] prefixs = dict["Prefix"].ToString().Split(',');
            foreach (var prefix in prefixs)
            {
                if (!string.IsNullOrEmpty(prefix) && model.TableInfo.Name.Contains(prefix))
                {
                    model.Name = model.TableInfo.Name.Replace(prefix, "");
                    break;
                }
            }
            model.PrimaryKey = dict["PrimaryKey"].ToString();

            model.Refresh = btn["Refresh"];
            model.Add = btn["Add"];
            model.Edit = btn["Edit"];
            model.Delete = btn["Delete"];
            model.Detail = btn["Detail"];
            model.Close = btn["Close"];
            model.BtnAuthorization = Convert.ToBoolean(dict["BtnAuthorization"]);
            model.ViewAuthorization = Convert.ToBoolean(dict["ViewAuthorization"]);

            model.ListCode = listCode;
            model.FormCode = formCode;

            outputDir = dict["OutputDir"].ToString();
            preview = Convert.ToBoolean(dict["Preview"]);

            doWork.RunWorkerAsync();
        }
        #endregion

        private void FrmCreateBuildH_SizeChanged(object sender, EventArgs e)
        {
            asc.controlAutoSize(this);
        }

        #region 开启工作
        void doWork_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            //如果用户取消了当前操作就关闭窗口。
            if (e.Cancelled)
            {
                this.lblMsg.Text = "用户取消操作！！！";
            }
            else
            {
                this.lblMsg.Text = "执行完成！！！";
                doWork.CancelAsync();

                
                if(preview)
                {
                    FrmBuildHCode form1 = new FrmBuildHCode(content);
                    form1.Text = model.TableInfo.Name;

                    ((FrmMain)(this.ParentForm)).ShowContent(form1.Text, form1);
                }
            }
        }

        void doWork_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            //修改进度条的显示。
            this.progressBar1.Value = e.ProgressPercentage;

            string message = e.UserState.ToString();
            this.lblMsg.Text = message;
        }

        void doWork_DoWork(object sender, DoWorkEventArgs e)
        {
            //在操作的过程中需要检查用户是否取消了当前的操作。
            if (doWork.CancellationPending == true)
            {
                e.Cancel = true;
                return;
            }

            BackgroundWorker bgWorker = sender as BackgroundWorker;

            string entityTempletePath = "\\Template\\BuildH\\Entity.cshtml";
            string bllTempletePath = "\\Template\\BuildH\\Bll.cshtml";
            string controllerTempletePath = "\\Template\\BuildH\\Controller.cshtml";
            string indexTempletePath = "\\Template\\BuildH\\Index.cshtml";
            string indexJsTempletePath = "\\Template\\BuildH\\IndexJs.cshtml";
            string formTempletePath = "\\Template\\BuildH\\Form.cshtml";
            string formJsTempletePath = "\\Template\\BuildH\\FormJs.cshtml";

            bgWorker.ReportProgress(1, "正在生成实体类");
            string entityContent = RazorHelper.RunCompile(entityTempletePath, model);

            bgWorker.ReportProgress(2, "正在生成业务类");
            string bllContent = RazorHelper.RunCompile(bllTempletePath, model);

            bgWorker.ReportProgress(3, "正在生成控制器");
            string controllerContent = RazorHelper.RunCompile(controllerTempletePath, model);

            bgWorker.ReportProgress(4, "正在生成主页面");
            string indexContent = RazorHelper.RunCompile(indexTempletePath, model);

            bgWorker.ReportProgress(5, "正在生成主页面Js");
            string indexJsContent = RazorHelper.RunCompile(indexJsTempletePath, model);

            bgWorker.ReportProgress(6, "正在生成表单页面");
            string formContent = RazorHelper.RunCompile(formTempletePath, model);

            bgWorker.ReportProgress(7, "正在生成表单页面Js");
            string formJsContent = RazorHelper.RunCompile(formJsTempletePath, model);


            if (!preview)
            {
                bgWorker.ReportProgress(8, "正在保存代码");

                string dirPath = outputDir + "\\BuildH\\" + model.Name+"\\";

                string entityPath = dirPath + "\\Entity\\" + model.Name + "Entity.cs";
                string bllPath = dirPath + "\\Bll\\" + model.Name + "Bll.cs";
                string controllerPath = dirPath + "\\Controller\\" + model.Name + "Controller.cs";
                string indexPath = dirPath + "\\Views\\" + model.Name + "\\Index.cshtml";
                string indexJsPath = dirPath + "\\Js\\" + model.Name + "\\Index.js";
                string formPath = dirPath + "\\Views\\" + model.Name + "\\Form.cshtml";
                string formJsPath = dirPath + "\\Js\\" + model.Name + "\\Form.js";

                DirectoryUtil.Write(entityPath, entityContent);
                DirectoryUtil.Write(bllPath, bllContent);
                DirectoryUtil.Write(controllerPath, controllerContent);
                DirectoryUtil.Write(indexPath, indexContent);
                DirectoryUtil.Write(indexJsPath, indexJsContent);
                DirectoryUtil.Write(formPath, formContent);
                DirectoryUtil.Write(formJsPath, formJsContent);

                System.Diagnostics.Process.Start(dirPath);
            }
            else
            {
                bgWorker.ReportProgress(8, "正在打开预览页");

                content.Add("entity", entityContent);
                content.Add("bll", bllContent);
                content.Add("controller", controllerContent);
                content.Add("index", indexContent);
                content.Add("indexJs", indexJsContent);
                content.Add("form", formContent);
                content.Add("formJs", formJsContent);
            }
        }

        #endregion
    }
}
